/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BaixaContaDialog.java
 *
 * Created on Aug 5, 2011, 10:34:47 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleConta;
import br.com.tbp.controle.ControleLancamento;
import br.com.tbp.exception.InputValidationException;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.model.domain.financeiro.Conta;
import br.com.tbp.model.domain.financeiro.Lancamento;
import br.com.tbp.model.domain.financeiro.TipoConta;
import br.com.tbp.utils.ColorUtils;
import br.com.tbp.utils.DateUtils;
import java.awt.Color;
import java.text.ParseException;
import java.util.Date;
import javax.swing.JOptionPane;
import um.filteredtext.number.CurrencyNumberAdapter;

/**
 *
 * @author Diego
 */
public class BaixaContaDialog extends javax.swing.JDialog {

    private Conta conta;
    private CurrencyNumberAdapter valorCurrency;
    private CurrencyNumberAdapter descontoCurrency;
    private CurrencyNumberAdapter totalCurrency;
    private boolean baixou = false;

    public BaixaContaDialog(java.awt.Frame parent, boolean modal, Conta c) {
        super(parent, "TBP - Baixa da conta nº " + c.getId(), modal);
        initComponents();
        configTextFieldsDeDinheiro();
        this.mostraInformacoes(c);
        this.setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        dataTextField = new org.jdesktop.swingx.JXDatePicker();
        jLabel2 = new javax.swing.JLabel();
        emissaoTextField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        atrasoTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        contaTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        valorTextField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        descontoTextField = new javax.swing.JTextField();
        totalLabel = new javax.swing.JLabel();
        totalTextField = new javax.swing.JTextField();
        cancelarButton = new javax.swing.JButton();
        baixaButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Data da baixa:");

        jLabel2.setText("Emissão:");

        emissaoTextField.setEditable(false);
        emissaoTextField.setFocusable(false);

        jLabel3.setText("Dias em atraso:");

        atrasoTextField.setEditable(false);
        atrasoTextField.setFocusable(false);

        jLabel4.setText("Conta:");

        contaTextField.setEditable(false);
        contaTextField.setFocusable(false);

        jLabel5.setText("Valor:");

        valorTextField.setEditable(false);
        valorTextField.setFocusable(false);

        jLabel6.setText("Desconto:");

        totalLabel.setText("Total recebido:");

        cancelarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/delete.png"))); // NOI18N
        cancelarButton.setText("Cancelar");
        cancelarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarButtonActionPerformed(evt);
            }
        });

        baixaButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/down.png"))); // NOI18N
        baixaButton.setText("Dar baixa");
        baixaButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                baixaButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(totalLabel)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(emissaoTextField)
                        .addComponent(dataTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(atrasoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(contaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(totalTextField, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(descontoTextField, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(valorTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(152, Short.MAX_VALUE)
                .addComponent(baixaButton, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(56, 56, 56)
                .addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {baixaButton, cancelarButton});

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {descontoTextField, emissaoTextField, totalTextField, valorTextField});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(dataTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(emissaoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(atrasoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(contaTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(valorTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(descontoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(totalLabel)
                    .addComponent(totalTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelarButton)
                    .addComponent(baixaButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelarButtonActionPerformed

    private void baixaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baixaButtonActionPerformed
        try {
            this.validarEntradaDoUsuario();

            Lancamento lc = new Lancamento(this.conta);
            lc.setData(dataTextField.getDate());
            try {
                Number valor = valorCurrency.getNumberFormat().parseNumber(valorTextField.getText());
                lc.setValor(new Double(valor.toString()));

                Number desconto = descontoCurrency.getNumberFormat().parseNumber(descontoTextField.getText());
                lc.setDesconto(new Double(desconto.toString()));

                Number total = totalCurrency.getNumberFormat().parseNumber(totalTextField.getText());
                lc.setTotal(new Double(total.toString()));
            } catch (ParseException pex) {
                System.out.println(pex.getMessage());
            }

            ControleLancamento controle = new ControleLancamento();
            controle.registrar(lc);
            this.baixarConta();
        } catch (InputValidationException ivex) {
            JOptionPane.showMessageDialog(null, ivex.getMessage(), "Atenção", JOptionPane.WARNING_MESSAGE);
            System.out.println(ivex.getMessage());
        } catch (PersistenciaException pex) {
            JOptionPane.showMessageDialog(null, pex.getMessage(), "Falha no sistema", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_baixaButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField atrasoTextField;
    private javax.swing.JButton baixaButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField contaTextField;
    private org.jdesktop.swingx.JXDatePicker dataTextField;
    private javax.swing.JTextField descontoTextField;
    private javax.swing.JTextField emissaoTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel totalLabel;
    private javax.swing.JTextField totalTextField;
    private javax.swing.JTextField valorTextField;
    // End of variables declaration//GEN-END:variables

    private void mostraInformacoes(Conta c) {
        this.conta = c;
        if (c.getTipo().equals(TipoConta.ENTRADA)) {
            totalLabel.setText("Total recebido: ");
            totalTextField.setForeground(ColorUtils.getVerdeEscuro());
        } else if (c.getTipo().equals(TipoConta.SAIDA)) {
            totalLabel.setText("Total pago: ");
            totalTextField.setForeground(Color.RED);
        }
        dataTextField.setDate(new Date());
        emissaoTextField.setText(DateUtils.dataObjetoParaString(c.getData()));
        atrasoTextField.setText("0");
        contaTextField.setText(c.getDescricao());
        if (c.getValor() != null) {
            valorTextField.setText(valorCurrency.getNumberFormat().formatNumber(c.getValor()));
            totalTextField.setText(totalCurrency.getNumberFormat().formatNumber(c.getValor()));
        } else {
            valorTextField.setText(null);
            totalTextField.setText(null);
        }
        descontoTextField.setText(descontoCurrency.getNumberFormat().formatNumber(new Double("0")));
    }

    private void configTextFieldsDeDinheiro() {
        valorCurrency = new CurrencyNumberAdapter(false);
        descontoCurrency = new CurrencyNumberAdapter(false);
        totalCurrency = new CurrencyNumberAdapter(false);

        valorTextField.addKeyListener(valorCurrency);
        valorTextField.addFocusListener(valorCurrency);

        descontoTextField.addKeyListener(descontoCurrency);
        descontoTextField.addFocusListener(descontoCurrency);

        totalTextField.addKeyListener(totalCurrency);
        totalTextField.addFocusListener(totalCurrency);
    }

    private void validarEntradaDoUsuario() throws InputValidationException {
        if (descontoTextField.getText().isEmpty()) {
            descontoTextField.requestFocus();
            throw new InputValidationException("O desconto R$ deve ser informado.");
        } else if (totalTextField.getText().isEmpty()) {
            totalTextField.requestFocus();
            throw new InputValidationException("O total R$ deve ser informado.");
        }
    }

    private void baixarConta() {
        Conta c = this.conta;
        c.setQuitada(true);
        try {
            ControleConta controle = new ControleConta();
            controle.editar(c);
            this.baixou = true;
            JOptionPane.showMessageDialog(null, "A conta: " + c.getDescricao() + "\nfoi baixada com sucesso.",
                    "Informação", JOptionPane.INFORMATION_MESSAGE);
            dispose();
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }

    public boolean isBaixou() {
        return baixou;
    }

    public void setBaixou(boolean baixou) {
        this.baixou = baixou;
    }
}
